﻿var obj = {
    BinLocationId: '',
    BinLocationNo: "",
    BinLocationName: "",
    BinLocationArea: "",
    MaximumLoad: "",
    BinLocationNotes: "",
    BinLocationState: "",
    WarehouseId: "",
    ReservoirId: "",
    createdBy: "",
    createdDate: "",
    updatedBy: "",
    updatedDate: "",
    deletedBy: "",
    deletedDate: "",
    isDeleted: "",
}

////仓库下拉框
//layui.use('form', function () {
//    var form = layui.form;
//    $.ajax({
//        url: "../Warehouse/GetWarehouseList",
//        type: "get",
//        data: { token: localStorage.getItem("token") },
//        success: function (data) {
//            var data = JSON.parse(data)
//            console.log(data.data)
//            var options = '<option value="">请选择</option>'; // 添加默认选项
//            $.each(data.data, function (item) {
//                options += '<option value="' + item.warehouseId + '">' + item.warehouseName + '</option>';
//            });
//            $("#warehouseId").html(options);
//            form.render('select'); // 重新渲染下拉框
//        },
//        error: function () {
//            console.log("获取数据失败");
//            // 可以考虑显示一个错误消息给用户
//        }
//    });
//});
layui.use(['table', 'dropdown', 'layer', 'form'], function () {

    var table = layui.table;
    var dropdown = layui.dropdown;
    var layer = layui.layer;
    var form = layui.form;
    var laypage = layui.laypage;
    function gettime() {
        // 获取当前日期时间
        var now = new Date();
        var year = now.getFullYear();
        var month = ("0" + (now.getMonth() + 1)).slice(-2);
        var day = ("0" + now.getDate()).slice(-2);
        var hours = ("0" + now.getHours()).slice(-2);
        var minutes = ("0" + now.getMinutes()).slice(-2);
        //var seconds = ("0" + now.getSeconds()).slice(-2);
        var serialNumber = "KW" + year + month + day + hours + minutes;
        var inputElement = document.getElementById('BinLocationNo1');
        inputElement.value = serialNumber;
    }
  
    //显示库位信息
    $(function () {
        Show();
        
    });
    //显示仓库
    window.one = function one() {
        $.ajax({
            url: "../Warehouse/GetWarehouseList",
            type: "get",
            data: { token: localStorage.getItem("token") },
            dataType: 'json', // 如果服务器返回的是 JSON 字符串，请移除这一行；如果返回的是 JSON 对象，请保留
            success: function (response) {
                // 如果服务器已经返回了 JSON 对象，则不需要再次解析
                var data = JSON.parse(response); // 请移除这一行，如果 response 已经是 JSON 对象
                console.log(data.data);
                
                var options = '<option value="">请选择</option>'; // 添加默认选项
                $.each(data.data, function (index, item) {
                    // 使用正确的参数：index（索引）和 item（当前元素）
                    options += '<option value="' + item.warehouseId + '">' + item.warehouseName + '</option>';

                });

                $("#warehouseId").html(options); // 设置下拉框的选项
                layui.form.render('select'); // 重新渲染下拉框（确保 layui.form 已经被正确加载）
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("获取数据失败: " + textStatus, errorThrown);
                // 可以考虑显示一个错误消息给用户，例如使用 layui 的 layer 模块
                // layer.msg('获取仓库列表失败，请稍后再试'); // 确保 layer 已经被加载和初始化
            }
        });
    }
    //显示库区
    window.two = function two() {
        var ids = $("#warehouseId").val(); // 从仓库ID输入框获取值
       
        console.log($("#warehouseId").val())
        if ($("#warehouseId").val() == "") {
            return;
        }
        else {
            var ss = $("#warehouseId").val();
            console.log(ss);
        }
        console.log(ss)
            $.ajax({
             url: "../Warehouse/GetReserList",
                type: "get",
                data: { WarehouseId: ss, token: localStorage.getItem("token") },
                dataType: 'json',
                success: function (response) {
                    var response = JSON.parse(response)
                    console.log(response.data)
                  
                      var options = '<option value="">请选择</option>';
                    $.each(response.data, function (index, item) {
                        options += '<option value="' + item.reservoirId + '">' + item.reservoirName + '</option>';
                    });
                
                    $("#reservoirId").html(options);
                    layui.form.render('select');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log("获取数据失败: " + textStatus, errorThrown);
                    layer.msg('获取仓库列表失败，请稍后再试'); // 确保 layer 已经被加载和初始化
                }
            });

        }
        //弹窗添加库位
    window.BinLocationAdd = function BinLocationAdd() {
        //显示仓库（二级联动）
        one()

        layer.open({
            type: 1, //page 层类型
            area: ['800px', '450px'],
            title: '新增库位',
            shade: 0.6, //遮罩透明度
            shadeClose: true, //点击遮罩区域，关闭弹层
            maxmin: true, //允许全屏最小化
            anim: 0, //0-6 的动画形式，- 1 不开启
            content: `
                  <div style="padding: 32px;">
               <form class="layui-form layui-form-pane" action="">
          <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">库位名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="BinLocationName1"  lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">库位编号：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="BinLocationNo1" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
        </div>
        <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">面积：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="BinLocationArea"  lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">最大载重量：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="MaximumLoad" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
        </div>
        <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">所属仓库：</label>
                     <div class="layui-input-block" onclick="two()" >
                <select id="warehouseId" lay-filter="aihao" ></select>
            </div>
                    
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">所属库区：</label>
                     <div class="layui-input-block">
                <select id="reservoirId" lay-filter="aihao"></select>
            </div>
                   
                </div>
        </div>
        <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">状态：</label>
                    
                    <div class="layui-input-block" >
      <input type="radio" name="BinLocationState1" value="false" title="启用">
      <input type="radio" name="BinLocationState1" value="true" title="禁用">

                    </div>
                   
                </div>
               
        </div>
        <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">备注：</label>
                  
                       <div class="layui-input-block">
      <textarea id="BinLocationNotes" placeholder="请输入内容" class="layui-textarea"></textarea>
    </div>
  </div>
                   
                </div>
               
        </div>
        <div class="layui-form-item">
         <button class="layui-btn" lay-submit lay-filter="demo2" onclick="location.href='/Warehouse/WarehouseShowBin'">取消</button>
                <button class="layui-btn" lay-submit lay-filter="demo2" onclick="DeviceAddBin()">确认</button>
        </div>
                                 </form>
                                   </div>`
        });
        
        form.render()
        gettime()
    }
    
    //添加库位信息
    window.DeviceAddBin = function DeviceAddBin() {
       

        obj.BinLocationName = $("#BinLocationName1").val()
        obj.BinLocationNo = $("#BinLocationNo1").val()
        obj.BinLocationArea = $("#BinLocationArea").val()
        obj.MaximumLoad = $("#MaximumLoad").val()
        obj.WarehouseId = $("#warehouseId").val()
        obj.ReservoirId = $("#reservoirId").val()
        obj.BinLocationState = $("[name='BinLocationState1']:checked").val()
        obj.BinLocationNotes = $("#BinLocationNotes").val()
        console.log(obj)
   $.ajax({
          
       url: '../Warehouse/AddWarehouseBin',
            type: 'post',
            data: {
                BinLocationNo: obj.BinLocationNo,
                BinLocationName: obj.BinLocationName,
                BinLocationArea: obj.BinLocationArea,
                MaximumLoad: obj.MaximumLoad,
                BinLocationNotes: obj.BinLocationNotes,
                BinLocationState: obj.BinLocationState,
                WarehouseId: obj.WarehouseId,
                ReservoirId: obj.ReservoirId,
                token: "",
            },
       //contentType: 'application/json',
      
            success: function (res) {
                console.log(res)
                var res = JSON.parse(res)
                if (res.code > 0) {
                    alert("添加成功")
                    window.location.href = '/Warehouse/WarehouseShowBin'
                }
                else {
                    alert("添加失败")
                }

            }
        })
    }


    //显示库位信息
    window.Show = function Show() {
        layui.use(function () {
            // 点击导出按钮
            document.getElementById('exportBtn').addEventListener('click', function () {
                var checkStatus = table.checkStatus('warehousetBin');  // 获取当前表格的选中状态
                var selectedData = checkStatus.data;  // 获取选中的数据
                if (selectedData.length === 0) {
                    alert('请先选择要导出的数据!');
                    return;
                }
                var filteredData = selectedData.map(function (item) {
                    // 创建一个新对象，只包含您想要的属性
                    return {
                        '库位Id': item.binLocationId,
                        '库位编号': item.binLocationNo,
                        '库位名称': item.binLocationName,
                        '面积': item.binLocationArea,
                        '最大载重量': item.maximumLoad,
                        '所属仓库': item.warehouseName, 
                        '所属库区': item.reservoirName,
                        '状态': item.binLocationState == false?"启用":"禁用",

                    };
                });

                // 使用 XLSX 导出选中的数据
                var wb = XLSX.utils.book_new();
                var ws = XLSX.utils.json_to_sheet(filteredData); // 将选中的数据转换为工作表
                XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

                // 导出为 Excel 文件
                XLSX.writeFile(wb, '库位列表.xlsx');
            });

            var BinLocationNo = $("#BinLocationNo").val();
            var BinLocationName = $("#BinLocationName").val();
            var BinLocationState = $("#BinLocationState2").val();
            // 先进行表格的初始渲染
            table.render({
                elem: '#warehousetBin',  // 表格元素的选择器
                page: {
                    limit: 5,
                    limits: [5, 8, 10]
                },
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'binLocationNo', title: '库位编号' },
                    { field: 'binLocationName', title: '库位名称' },
                    { field: 'binLocationArea', title: '面积' },
                    { field: 'maximumLoad', title: '最大载重量' },
                    { field: 'warehouseName', title: '所属仓库' },
                    { field: 'reservoirName', title: '所属库区' },
                    {
                        field: 'binLocationState', title: '状态', templet: function (x) {
                            if (x.binLocationState === true) {
                                return '<span style="color: red;">禁用</span>'
                            }
                            else {
                                return '<span style="color: green;">启用</span>'
                            }
                        } },
                  
                    {
                        field: '', title: '操作', templet: function (d) {
                            return '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="FanUpdateBin(' + d.binLocationId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="IsDel(' + d.binLocationId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                        }

                    }
                ]],
                // 初始时可以先不加载数据，等待 ajax 请求成功后再更新
                data: []
            });

            // 创建表格实例
            $.ajax({
                url: "../Warehouse/GetWarehouseShowBin",
                type: "get",
                data: {
                    PageIndex: 1,
                    PageSize: 100,
                    token: "",
                    BinLocationNo: BinLocationNo,
                    BinLocationName: BinLocationName,
                    BinLocationState: BinLocationState
                },

                success: function (data) {
                    data = JSON.parse(data);
                    console.log(data.data.list);
                    // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
                    table.reload('warehousetBin', {
                        page: {
                            limit: 5,
                            limits: [5, 8, 10]
                        },
                        data: data.data.list
                    });
                },
                error: function () {
                    console.log("请求失败");
                }
            });
        });
    }
    //单删库位信息
    window.IsDel = function IsDel(binLocationId) {
        var token = localStorage.getItem("token")
       
        layer.confirm("确认删除吗", function () {
            $.ajax({
                url: '../Warehouse/DelWarehouseBin',
                data: { BinLocationId: binLocationId, token: token },
                type: 'post',
                success: function (res) {
                    console.log(res);
                    var res = JSON.parse(res);
                    if (res.code==1) {
                        layer.msg("删除成功", { icon: 1 });
                        Show();
                    } else {
                        layer.msg("删除失败", { icon: 2 });
                    }
                }
            });
        });
    }
    //反填修改
    var obj1 = {
        BinLocationId: "",
        BinLocationNo: "",
        BinLocationName: "",
        BinLocationArea: "",
        MaximumLoad: "",
        BinLocationNotes: "",
        BinLocationState: "",
        WarehouseId: "",
        ReservoirId: "",
        createdBy: "",
        createdDate: "",
        updatedBy: "",
        updatedDate: "",
        deletedBy: "",
        deletedDate: "",
        isDeleted: "",
    }
    window.FanUpdateBin = function FanUpdateBin(binLocationId) {
        $.ajax({
            url: '../Warehouse/GetByWarehouseBin',
            data: {
                BinLocationId: binLocationId,
                token: ""
            },
            type: 'Get',
            success: function (res) {

                var res = JSON.parse(res)
                console.log(res)
                $.each(res, function () {
                    $("#BinLocationName1").val(this.binLocationName)
                    $("#BinLocationNo1").val(this.binLocationNo)
                    $("#BinLocationArea").val(this.binLocationArea)
                    $("#MaximumLoad").val(this.maximumLoad)
                    one()
                    $("#warehouseId").val(this.warehouseId)
                    two()
                    $("#reservoirId").val(this.reservoirId)
                    $("[name='BinLocationState1'][value='" + this.binLocationState + "']").prop("checked", true)
                    $("#BinLocationNotes").val(this.binLocationNotes)
                    localStorage.setItem("binLocationId", this.binLocationId)
                    localStorage.setItem("createdDate", this.createdDate)
                    localStorage.setItem("createdBy", this.createdBy)
                    console.log(localStorage.getItem("createdBy"))

                    form.render('checkbox'); // 重新渲染checkbox表单元素
                })
            }
        })
        layer.open({
            type: 1, //page 层类型
            area: ['800px', '400px'],
            title: '修改库位',
            shade: 0.6, //遮罩透明度
            shadeClose: true, //点击遮罩区域，关闭弹层
            maxmin: true, //允许全屏最小化
            anim: 0, //0-6 的动画形式，- 1 不开启
            content: `
                  <div style="padding: 32px;">
               <form class="layui-form layui-form-pane" action="">
          <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">库位名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="BinLocationName1"  lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">库位编号：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="BinLocationNo1" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
        </div>
        <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">面积：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="BinLocationArea"  lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">最大载重量：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="MaximumLoad" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
        </div>
        <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">所属仓库：</label>
                     <div class="layui-input-block" onclick="two()" >
                <select id="warehouseId" lay-filter="aihao" ></select>
            </div>
                    
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">所属库区：</label>
                     <div class="layui-input-block">
                <select id="reservoirId" lay-filter="aihao"></select>
            </div>
                   
                </div>
        </div>
        <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">状态：</label>
                    
                    <div class="layui-input-block" >
      <input type="radio" name="BinLocationState1" value="false" title="启用">
      <input type="radio" name="BinLocationState1" value="true" title="禁用">

                    </div>
                   
                </div>
               
        </div>
        <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">备注：</label>
                  
                       <div class="layui-input-block">
      <textarea id="BinLocationNotes" placeholder="请输入内容" class="layui-textarea"></textarea>
    </div>
  </div>
                   
                </div>
               
        </div>
        <div class="layui-form-item">
         <button class="layui-btn" lay-submit lay-filter="demo2" onclick="location.href='/Warehouse/WarehouseShowBin'">取消</button>
                <button class="layui-btn" lay-submit lay-filter="demo2" onclick="UpdateBin()">确认</button>
        </div>
                                 </form>
                                   </div>`,

          
   });
        form.render()
        //修改库位信息
        window.UpdateBin = function UpdateBin() {
            //BinLocationName = $("#BinLocationName1").val()
            //BinLocationNo = $("#BinLocationNo1").val()
            //BinLocationArea = $("#BinLocationArea").val()
            //MaximumLoad = $("#MaximumLoad").val()
            //WarehouseId = $("#WarehouseId").val()
            //ReservoirId = $("#ReservoirId").val()
            //BinLocationState = $("[name='BinLocationState1']:checked").val()
            //BinLocationNotes = $("#BinLocationNotes").val()
            //UpdatedBy = "李四"
            //updatedDate = new Date()
           
            var obj2 = {
                BinLocationId: "",
                BinLocationNo: "",
                BinLocationName: "",
                BinLocationArea: "",
                MaximumLoad: "",
                BinLocationNotes: "",
                BinLocationState: "",
                WarehouseId: "",
                ReservoirId: "",
                createdBy: "",
                createdDate: "",
                updatedBy: "",
                updatedDate: "",
                deletedBy: "",
                deletedDate: "",
                isDeleted: "",
            }
            obj2.BinLocationId = localStorage.getItem("binLocationId"),
                obj2.BinLocationNo = $("#BinLocationNo1").val(),
                obj2.BinLocationName = $("#BinLocationName1").val(),
                obj2.BinLocationArea = $("#BinLocationArea").val(),
                obj2.MaximumLoad = $("#MaximumLoad").val(),
                obj2.BinLocationNotes = $("#BinLocationNotes").val(),
                obj2.BinLocationState = $("[name='BinLocationState1']:checked").val(),
                obj2.WarehouseId = $("#warehouseId").val(),
                obj2.ReservoirId = $("#reservoirId").val(),
                obj2.createdBy =localStorage.getItem("createdBy"),
                obj2.createdDate =localStorage.getItem("createdDate"),
                obj2.updatedBy = "李四",
                obj2.updatedDate = new Date(),
                //obj2.deletedBy = obj1.deletedBy,
                //obj2.deletedDate = obj1.deletedDate,
            console.log(obj2)
            var token = localStorage.getItem("token")
            $.ajax({
                url: '../Warehouse/UpdateWarehouseBin',
                type: 'post',
                data: { dto: obj2, token: token },
                //contentType: 'application/json',
                success: function (res) {
                    console.log(res)
                    var res = JSON.parse(res)
                    if (res.code > 0) {
                        alert("修改成功")
                        window.location.href = '/Warehouse/WarehouseShowBin'
                    }
                    else {
                        alert("修改失败")
                    }

                }
            })
        }
    }

});



